package com.yzy.config.intercepor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.yzy.common.Code;
import com.yzy.entity.Teacher;
import com.yzy.exception.ServiceException;
import com.yzy.service.impl.TeacherServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 杨子宇
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private TeacherServiceImpl teacherService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从 http 请求头中取出 token
        String token = request.getHeader("Tea-token");

        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(Code.code_401, "亲爱的教师，您还没有登录，请先登录！");
        }

        // 获取 token 中的 teacher id
        String teacherId;
        try {
            teacherId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new ServiceException(Code.code_401, "教师的token验证失败！");
        }


        Teacher teacher = teacherService.getById(teacherId);
        if (teacher == null) {
            throw new ServiceException(Code.code_401, "该教师不存在，请重新登录！");
        }

        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(teacher.getUsername())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException(Code.code_401, "亲爱的教师，您的身份已过期，请重新登录！");
        }

        return true;
    }
}
